package com.itheima.search.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.address}")
    private String esAddress; // 格式如 http://192.168.12.168:9200

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 解析esAddress
        String[] parts = esAddress.split(":");
        // 获取host和port
        String host = parts[1].replace("//", "");
        int port = Integer.parseInt(parts[2]);

        // 创建ObjectMapper实例并注册JavaTimeModule
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        // 创建RestHighLevelClient实例
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, port, "http"))
        );
    }
}